/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

 /**
   * Global variables to hold the profile and email data.
   */
   var profile;
   var registered;
   
(function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js?onload=render';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  })();

 function render() {
    registered = false;
    var additionalParams = {
        'callback':signinCallback,
        'clientid':'555493968713-0g1jcucs034kb29ostqt7n36aprjlrf7.apps.googleusercontent.com',
        'cookiepolicy':'single_host_origin',
        'requestvisibleactions':'http://schemas.google.com/AddActivity',
        'scope':'https://www.googleapis.com/auth/plus.login'
    };
    var signinButton = document.getElementById("googleButton");
    signinButton.addEventListener("click", function() {
        gapi.auth.signIn(additionalParams);
    }, false);
 }
 
 function signinCallback(authResult) {
    if (authResult['access_token']) {
        //document.getElementById('googleButton').setAttribute('style', 'display: none'); //remove the login button
        if (authResult) {
            if (authResult['error'] === undefined){
              toggleElement('googleButton'); // Hide the sign-in button after successfully signing in the user.
              gapi.client.load('plus','v1', loadProfile);  // Trigger request to get the email address.
            } else {
              console.log('An error occurred');
            }
          } else {
            console.log('Empty authResult');  // Something went wrong
          }
    } else if (authResult['error']) {
        console.log('Sign-in state: ' + authResult['error']);
    }
 }

  /**
   * Uses the JavaScript API to request the user's profile, which includes
   * their basic information. When the plus.profile.emails.read scope is
   * requested, the response will also include the user's primary email address
   * and any other email addresses that the user made public.
   */
  function loadProfile(){
    var request = gapi.client.plus.people.get( {'userId' : 'me'} );
    request.execute(loadProfileCallback);
  }

  /**
   * Callback for the asynchronous request to the people.get method. The profile
   * and email are set to global variables. Triggers the user's basic profile
   * to display when called.
   */
  function loadProfileCallback(obj) {
    profile = obj;
    email = obj['emails'][0].value; // get the email from the filtered results, should always be defined.
    var str = obj['displayName'];
    var n = str.indexOf(" ");
    name = str.substring(0,n);
    surname = str.substring(n+1,str.length);
    
    if(!registered) {
        registered = true;
        console.log("AJAX call");     
        $.post("Controller",{"hidden":"google",
                           "nome":name,
                           "cognome":surname,
                           "email":email},
               function(){
                    window.location = 'http://localhost:8080/csm-catering-war/'; 
               },"json");
       }
                       
    toggleElement('profile');
  }

  /**
   * Utility function to show or hide elements by their IDs.
   */
  function toggleElement(id) {
    var el = document.getElementById(id);
    if (el.getAttribute('class') == 'hide') {
      el.setAttribute('class', 'show');
    } else {
      el.setAttribute('class', 'hide');
    }
  }
